package com.kitty.common.schedule;

import cn.hutool.core.lang.Assert;
import com.kitty.common.schedule.entity.SpringScheduledCron;
import com.kitty.common.schedule.service.SpringScheduledCronService;
import com.kitty.common.schedule.task.ScheduledOfTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
@Slf4j
public class InitTask implements CommandLineRunner {
    @Autowired
    CronTaskRegistrar cronTaskRegistrar;
    @Autowired
    private ApplicationContext context;
    @Autowired
    private SpringScheduledCronService cronRepository;


    @Override
    public void run(String... args) throws Exception {
        for (SpringScheduledCron springScheduledCron : cronRepository.findAll()) {
            Class<?> clazz;
            Object task;
            try {
                clazz = Class.forName(springScheduledCron.getCron_key());
                task = context.getBean(clazz);
            } catch (ClassNotFoundException e) {
                log.info("spring_scheduled_cron表数据" + springScheduledCron.getCron_key() + "有误", e);
                throw new IllegalArgumentException("spring_scheduled_cron表数据" + springScheduledCron.getCron_key() + "有误", e);
            } catch (BeansException e) {
                log.info(springScheduledCron.getCron_key() + "未纳入到spring管理", e);
                throw new IllegalArgumentException(springScheduledCron.getCron_key() + "未纳入到spring管理", e);
            }
            Assert.isAssignable(ScheduledOfTask.class, task.getClass(), "定时任务类必须实现ScheduledOfTask接口");
            // 可以通过改变数据库数据进而实现动态改变执行周期
            String cronExpression = cronRepository.findByCronKey(springScheduledCron.getCron_key()).get(0).getCron_expression();
            cronTaskRegistrar.addCronTask((Runnable) task,cronExpression);
        }
    }
}
